package com.raojunxue.company.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
	
	private static final String COLON = ":";
	private static final String COMMA = ",";
	private static final String NUMBER_REGEX = "[0-9]*";
	private static final int RANDOM_SEED = 999999999;

	public static String getRandomNumber(){
		Random random = new Random();
		return String.valueOf(random.nextInt(RANDOM_SEED));
	}
	
	public static boolean isNumeric(String str)
	{
		Pattern pattern = Pattern.compile(NUMBER_REGEX);
		Matcher isNum = pattern.matcher(str);
		return isNum.matches();
	}
	
	public static Map<String, Integer> parseSIJson(String json){
		Map<String, Integer> datas = new HashMap<String, Integer>();
		if(json != null && json.length() > 0){
			String[] keyValues = json.split(COMMA);
			for(String keyValue:keyValues){
				if(keyValue.contains(COLON)){
					String[] values = keyValue.split(COLON);
					Integer value = datas.get(values[1]);
					if(value != null)
						datas.put(values[0], value + Integer.valueOf(values[1]));
					else{
						datas.put(values[0], Integer.valueOf(values[1]));
					}
				}
			}
		}
		return datas;
	}
	
	public static Map<String, String> parseSSJson(String json){
		Map<String, String> datas = new HashMap<String, String>();
		if(json != null && json.length() > 0){
			String[] keyValues = json.split(COMMA);
			for(String keyValue:keyValues){
				if(keyValue.contains(COLON)){
					String[] values = keyValue.split(COLON);
					datas.put(values[0], values[1]);
				}
			}
		}
		return datas;
	}
	
	public static boolean match(String value, String regex){
		Pattern pattern = null;
		Matcher matcher = null;
		boolean rs = false;
		pattern = Pattern.compile(regex);
		matcher = pattern.matcher(value);
		rs = matcher.find();
		if(rs)
			return true;
		return false;
	}

	public static List<String> split(String content, String regex) {
		String[] temps = content.split(regex);
		List<String> results = new ArrayList<String>();
		int start = 0;
		for(String temp:temps){
			if(temp.length() > 0){
				int pos = content.indexOf(temp);
				int end = pos + temp.length();
				if(pos >= 0 && start < end && end < content.length()){
					results.add(content.substring(start, end));
					start = end;
				}
				else if(pos >= 0 && start < content.length()){
					results.add(content.substring(start));
					break;
				}
			}
		}
		return results;
	}
}
